package com.xyauto.theme.fragment

import android.content.Context
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ToastUtils
import com.xyauto.theme.BuildConfig
import com.xyauto.theme.R
import com.xyauto.theme.base.BaseListFragment
import com.xyauto.theme.bean.IThemeBean
import com.xyauto.theme.utils.startDetails
import com.xyauto.theme.vm.MainListViewModel

class MainListFragment : BaseListFragment<ThemeListAdapter, IThemeBean, MainListViewModel>() {

    companion object {
        private const val ARGUMENT_KEY_TYPE = "ARGUMENT_KEY_TYPE"

        fun newInstance(type: String) = MainListFragment().apply {
            arguments = Bundle().apply {
                putString(ARGUMENT_KEY_TYPE, type)
            }
        }
    }

    private lateinit var mType: String
    private var hasNext = false

    override fun getLayoutId(): Int = R.layout.fragment_main_list

    override fun newLayoutManager(context: Context) = GridLayoutManager(context, 3, RecyclerView.VERTICAL, false)

    override fun initData() {
        mType = arguments?.getString(ARGUMENT_KEY_TYPE) ?: ""
        viewModel.nextData.observe(this) {
            hasNext = it
        }
        viewModel.listData.observe(this) {
            onSuccessList(it, hasNext)
        }
        onRefresh()
    }

    override fun onLoadData(isRefresh: Boolean, pagerNumber: Int) {
        viewModel.getData(mType, pagerNumber)
    }


    override fun initListener() {
        mAdapter.setOnItemClickListener { _, _, p ->
            startDetails(mAdapter.getItem(p))
        }
    }


    override fun showError(msg: String, code: Int) {
        super.showError(msg, code)
        ToastUtils.showLong(msg)
        onFailureList()
    }

}